<template>
  <div class="pic-container">
    <div class="app-header">
      <h1 class="app-title">AI 灵魂画手 🎨</h1>
      <p class="app-description">零基础创意绘画应用，简单涂鸦几笔，AI 即可将其补充完善为精美的艺术插画。降低艺术创作门槛，体验从简单涂鸦到专业插画的转变过程，激发创造力和想象力。</p>
    </div>
    
    <div class="drawing-area">
      <canvas 
        ref="canvas" 
        @mousedown="startDrawing" 
        @mousemove="draw" 
        @mouseup="stopDrawing"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="stopDrawing"
      ></canvas>
    </div>
    
    <div class="tools">
      <div class="color-picker">
        <span>颜色:</span>
        <input type="color" v-model="currentColor">
      </div>
      
      <div class="line-width">
        <span>线条粗细:</span>
        <input type="range" min="1" max="20" v-model.number="lineWidth">
      </div>
      
      <div class="buttons">
        <button @click="clearCanvas">清除</button>
        <button @click="undo" :disabled="history.length === 0">撤销</button>
        <button @click="generateImage" :disabled="isGenerating">
          {{ isGenerating ? '生成中...' : '生成图像' }}
        </button>
      </div>
      
      <div class="style-selector">
        <span>风格选择:</span>
        <select v-model="selectedStyle">
          <option value="realistic">写实</option>
          <option value="cartoon">卡通</option>
          <option value="oil">油画</option>
          <option value="watercolor">水彩</option>
        </select>
      </div>
    </div>
    
    <div v-if="generatedImage" class="result">
      <h3>生成结果</h3>
      <img :src="generatedImage" alt="AI生成的图像">
      <div class="action-buttons">
        <button @click="saveImage">保存图像</button>
        <button @click="shareImage">分享</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'PicGame',
  data() {
    return {
      // Canvas元素引用
      canvas: null,
      // Canvas 2D渲染上下文
      ctx: null, 
      // 是否正在绘制的状态标志
      isDrawing: false,
      // 当前选择的绘制颜色
      currentColor: '#000000',
      // 当前线条宽度
      lineWidth: 5,
      // 绘制历史记录,用于撤销功能
      history: [],
      // 是否正在生成AI图像的状态标志
      isGenerating: false,
      // 生成的AI图像URL
      generatedImage: null,
      // 当前选择的图像风格
      selectedStyle: 'realistic',
      // 上一次绘制坐标的X值
      lastX: 0,
      // 上一次绘制坐标的Y值
      lastY: 0    };
  },
  mounted() {
    this.initCanvas();
    window.addEventListener('resize', this.resizeCanvas);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCanvas);
  },
  methods: {
    initCanvas() {
      this.canvas = this.$refs.canvas;
      this.ctx = this.canvas.getContext('2d');
      this.resizeCanvas();
      
      // 设置画布背景为白色
      this.ctx.fillStyle = '#ffffff';
      this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    },
    
    resizeCanvas() {
      const container = this.canvas.parentElement;
      const oldData = this.ctx ? this.ctx.getImageData(0, 0, this.canvas.width, this.canvas.height) : null;
      
      this.canvas.width = container.clientWidth;
      this.canvas.height = container.clientHeight;
      
      if (oldData) {
        this.ctx.putImageData(oldData, 0, 0);
      } else {
        // 重新设置白色背景
        this.ctx.fillStyle = '#ffffff';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
      }
    },
    
    startDrawing(event) {
      this.isDrawing = true;
      const { offsetX, offsetY } = this.getCoordinates(event);
      this.lastX = offsetX;
      this.lastY = offsetY;
      
      // 保存当前画布状态用于撤销
      this.saveState();
    },
    
    draw(event) {
      if (!this.isDrawing) return;
      
      const { offsetX, offsetY } = this.getCoordinates(event);
      
      this.ctx.beginPath();
      this.ctx.moveTo(this.lastX, this.lastY);
      this.ctx.lineTo(offsetX, offsetY);
      this.ctx.strokeStyle = this.currentColor;
      this.ctx.lineWidth = this.lineWidth;
      this.ctx.lineCap = 'round';
      this.ctx.stroke();
      
      this.lastX = offsetX;
      this.lastY = offsetY;
    },
    
    stopDrawing() {
      this.isDrawing = false;
    },
    
    handleTouchStart(event) {
      event.preventDefault();
      const touch = event.touches[0];
      const mouseEvent = {
        clientX: touch.clientX,
        clientY: touch.clientY
      };
      this.startDrawing(mouseEvent);
    },
    
    handleTouchMove(event) {
      event.preventDefault();
      const touch = event.touches[0];
      const mouseEvent = {
        clientX: touch.clientX,
        clientY: touch.clientY
      };
      this.draw(mouseEvent);
    },
    
    getCoordinates(event) {
      const rect = this.canvas.getBoundingClientRect();
      return {
        offsetX: event.clientX - rect.left,
        offsetY: event.clientY - rect.top
      };
    },
    
    clearCanvas() {
      this.saveState();
      this.ctx.fillStyle = '#ffffff';
      this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    },
    
    saveState() {
      const state = this.ctx.getImageData(0, 0, this.canvas.width, this.canvas.height);
      this.history.push(state);
      
      // 限制历史记录长度，避免内存占用过大
      if (this.history.length > 10) {
        this.history.shift();
      }
    },
    
    undo() {
      if (this.history.length > 0) {
        const previousState = this.history.pop();
        this.ctx.putImageData(previousState, 0, 0);
      }
    },
    
    async generateImage() {
      this.isGenerating = true;
      
      try {
        // 将画布转换为base64格式
        const imageData = this.canvas.toDataURL('image/png');
        
        // 构建提示词，根据选择的风格调整
        let stylePrompt = '';
        switch(this.selectedStyle) {
          case 'realistic':
            stylePrompt = 'realistic style, detailed, high quality';
            break;
          case 'cartoon':
            stylePrompt = 'cartoon style, vibrant colors, cute';
            break;
          case 'oil':
            stylePrompt = 'oil painting style, textured, artistic';
            break;
          case 'watercolor':
            stylePrompt = 'watercolor style, soft colors, flowing';
            break;
        }
        
        // 调用图像生成API
        const response = await axios.post('https://api.siliconflow.cn/v1/images/generations', {
          model: 'Kwai-Kolors/Kolors',
          prompt: `Transform this sketch into a ${stylePrompt} image`,
          image_size: '1024x1024',
          batch_size: 1,
          num_inference_steps: 20,
          guidance_scale: 7.5,
          image: imageData
        }, {
          headers: {
            Authorization: 'Bearer '+ process.env.VUE_APP_API_KEY,
            'Content-Type': 'application/json'
          }
        });
        
        // 处理返回的图像
        if (response.data && response.data.images && response.data.images.length > 0) {
          this.generatedImage = response.data.images[0].url;
        }
      } catch (error) {
        console.error('生成图像失败:', error);
        alert('生成图像失败，请稍后再试');
      } finally {
        this.isGenerating = false;
      }
    },
    
    saveImage() {
      if (!this.generatedImage) return;
      
      // 创建一个临时链接用于下载
      const link = document.createElement('a');
      link.href = this.generatedImage;
      link.download = `ai-drawing-${new Date().getTime()}.png`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    
    shareImage() {
      if (!this.generatedImage) return;
      
      // 检查是否支持Web Share API
      if (navigator.share) {
        navigator.share({
          title: 'AI灵魂画手',
          text: '看看我用AI灵魂画手创作的作品!',
          url: this.generatedImage
        }).catch(error => {
          console.error('分享失败:', error);
        });
      } else {
        // 如果不支持，可以提供复制链接的功能
        const dummy = document.createElement('textarea');
        document.body.appendChild(dummy);
        dummy.value = this.generatedImage;
        dummy.select();
        document.execCommand('copy');
        document.body.removeChild(dummy);
        alert('图片链接已复制到剪贴板，您可以手动分享');
      }
    }
  }
};
</script>

<style scoped>
.pic-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 15px;
}

.app-header {
  text-align: center;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f0f8ff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.app-title {
  color: #2c3e50;
  margin-bottom: 10px;
  font-size: 28px;
}

.app-description {
  color: #5a6a7a;
  line-height: 1.5;
  margin: 0;
  font-size: 16px;
}

.drawing-area {
  flex: 1;
  border: 2px solid #333;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 15px;
  background-color: #f5f5f5;
}

canvas {
  width: 100%;
  height: 100%;
  display: block;
  cursor: crosshair;
}

.tools {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  padding: 10px;
  background-color: #eaeaea;
  border-radius: 8px;
  margin-bottom: 15px;
}

.color-picker,
.line-width,
.style-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.buttons {
  display: flex;
  gap: 10px;
}

button {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  background-color: #4CAF50;
  color: white;
  cursor: pointer;
  font-weight: bold;
}

button:hover {
  background-color: #45a049;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.result {
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.result img {
  max-width: 100%;
  border-radius: 4px;
  margin: 10px 0;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 10px;
}

@media (max-width: 768px) {
  .tools {
    flex-direction: column;
    align-items: stretch;
  }
  
  .buttons {
    justify-content: space-between;
  }
}
</style>